package com.vandagroup.md5;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

import COM.claymoresystems.ptls.LoadProviders;

public class MD5password{

	private byte [] salt=null;
	private SecureRandom rng=null;

	static{
		LoadProviders.init();
	}

	public MD5password(SecureRandom rng) {
		this.rng = rng;
		salt = new byte[20];
	}
	public byte[] GenerateHash(String pw)
		throws NoSuchAlgorithmException,NoSuchProviderException{
		byte[] result=null;
		try{
			rng.nextBytes(salt);
			MessageDigest alg = MessageDigest.getInstance("MD5");
			alg.update(salt);
			alg.update(pw.getBytes());
			result=alg.digest();
		}
		catch (NoSuchAlgorithmException e){
			throw new NoSuchAlgorithmException(e.toString());
		}

		return result;
	}
	public byte[] GetSalt(){
		return salt;
	}
	private static final boolean notEquals(byte[] a, byte[] b){
		for (int i = 0; i < a.length; i++)
		{
			if (a[i] != b[i])
				return true;
		}
		return false;
	}
	public boolean VerifyHash(String pw,byte[] salt,byte[] hash)
		throws NoSuchAlgorithmException,NoSuchProviderException{
		try{
			MessageDigest alg = MessageDigest.getInstance("MD5");
			alg.update(salt);
			alg.update(pw.getBytes());
			byte[] result=alg.digest();
			if (notEquals(result,hash))
				return false;
			else
				return true;
			}
		catch (NoSuchAlgorithmException e){
			throw new NoSuchAlgorithmException(e.toString());
		}
	}
}
